/**
 * 
 */
package info.niwota.profile;

import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;

/**
 * @author qiangli
 *
 */
public class Locations {

	/**
	 * 
	 */
	private Locations() {
	}

	public static String getLocation(Context ctx) {
		try {
			LocationManager lm = (LocationManager) ctx
					.getSystemService(Context.LOCATION_SERVICE);
			Criteria c = new Criteria();
			// c.setAccuracy(Criteria.ACCURACY_FINE);
			c.setAltitudeRequired(false);
			c.setBearingRequired(false);
			c.setCostAllowed(true);
			c.setPowerRequirement(Criteria.POWER_LOW);
			//
			List<String> p = lm.getProviders(c, true);
			//
			Location l = null;
			for (int i = p.size() - 1; i >= 0; i--) {
				l = lm.getLastKnownLocation(p.get(i));
				if (l != null) {
					String s = formatLocation(ctx, l);
					if (s != null) {
						return s;
					}
				}
			}
		} catch (Error e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String formatLocation(Context ctx, Location l)
			throws Exception {
		double la = l.getLatitude();
		double lo = l.getLongitude();
		Geocoder gc = new Geocoder(ctx, Locale.getDefault());
		List<Address> al = gc.getFromLocation(la, lo, 1);
		if (al == null || al.size() <= 0) {
			return null;
		}
		Address adr = al.get(0);
		StringBuilder sb = new StringBuilder();
		String fn = adr.getFeatureName();
		String cc = adr.getCountryCode();
		String aa = adr.getAdminArea();
		String sa = adr.getSubAdminArea();

		String sep = ", ";
		sb.append(nvl(fn, " "));
		sb.append(nvl(sa, sep));
		sb.append(nvl(aa, sep));
		sb.append(nvl(cc, " "));

		return sb.toString();
	}

	private static String nvl(String s, String delimit) {
		return (s == null ? "" : s + delimit);
	}


}
